package com.shuma.shopmanage.shopmodule.service.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuma.shopmanage.common.utils.RedisConstants;
import com.shuma.shopmanage.model.shop.model.Category;
import com.shuma.shopmanage.model.shop.vo.CategoryVo;
import com.shuma.shopmanage.shopmodule.mapper.CategoryMapper;
import com.shuma.shopmanage.shopmodule.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wp
 * @data 2023/10/25
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    @Cacheable(value = RedisConstants.BASE_PREFIX, key = "T(com.shuma.shopmanage.common.utils.RedisConstants).CATEGORY_LIST")
    public List<CategoryVo> getCategory() {

        List<Category> categories = query().list();
        Map<Long, CategoryVo> resultMap = categories.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toMap(CategoryVo::getCatId, categoryVo -> categoryVo));

        Map<Long, Category> map = categories.stream().
                collect(Collectors.toMap(Category::getCatId, category -> category));

        map.forEach((key, value) -> {
            if (value.getLeaf()) {
                resultMap.get(key).setSonCategories(null);
            }
            if (!ObjectUtils.isEmpty(value.getParentCatId())) {
                List<CategoryVo> sonCategories = resultMap.
                        get(value.getParentCatId()).getSonCategories();
                sonCategories.add(resultMap.get(key));
            }
        });
        ArrayList<CategoryVo> result = new ArrayList<>();
        for (CategoryVo categoryVo : resultMap.values()) {
            if (!ObjectUtils.isEmpty(categoryVo.getSonCategories())) {
                result.add(categoryVo);
            }
        }

        return result;
    }


}
